package com.ljx.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.ljx.R;
import com.ljx.exception.GuliException;
import com.ljx.service.VodServiceImpl;
import com.ljx.utils.ConstantVodUtils;
import com.ljx.utils.InitVodClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author 李加喜
 * @date 2020/9/27 0027 10:45
 * @Email 1129071273@qq.com
 */
@Api(description = "上传删除视频")
@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {
    @Autowired
    private VodServiceImpl vodService;
    //上传视频到阿里云
    @ApiOperation("上传视频到阿里云")
    @PostMapping("/updateVdo")
    public R updateVdo(MultipartFile file){
        String vdoId=vodService.upadteFile(file);
        System.out.println(vdoId);
        return R.ok().data("vdoId",vdoId);
    }
    //根据视频的Id删除视频
    @DeleteMapping("/delVdo/{id}")
    public R delVdo(@PathVariable String id){
        //把视频在阿里云里面删除
        //初始化对象
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //建立request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request传递视频的Id
            request.setVideoIds(id);
            //调用初始化对象进行删除
            client.getAcsResponse(request);
            return R.ok();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new GuliException(20001,"对不起删除失败");
        }
    }
    //删除多个视频的方法
    @DeleteMapping("/deletebatch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);
        return R.ok();
    }
    //获取视频的凭证
    @GetMapping("/getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id){
        //创建初始化对象
        try {
            //创建初始化对象
            DefaultAcsClient client =
                    InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        }catch(Exception e) {
            throw new GuliException(20001,"获取凭证失败");
        }

    }
}
